package com.hatricks.is.base.jol;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import javafx.scene.paint.Stop;
import lombok.SneakyThrows;
import org.openjdk.jol.info.GraphLayout;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.concurrent.TimeUnit;

/**
 * @packageName: com.hatricks.base.jol
 * @className: ObjectUse
 * @author: yanyuhui yanyh@glodon.com
 * @date: 2022/9/2 17:31
 * @description: 计算对象的大小（单位为字节）：ClassLayout.parseInstance(obj).instanceSize()
 * 查看对象内部信息： ClassLayout.parseInstance(obj).toPrintable()
 * 查看对象外部信息：包括引用的对象：GraphLayout.parseInstance(obj).toPrintable()
 * 查看对象占用空间总大小：GraphLayout.parseInstance(obj).totalSize()
 * <p>
 * 2000 0000 两千万数据 占内存 > 1.6g
 */
public class MemoryUse {
    @SneakyThrows
    public static void main(String[] args) {
//        System.out.println(ClassLayout.parseInstance(list).instanceSize());
//        System.out.println("==============");
//        System.out.println(GraphLayout.parseInstance(list).totalSize());
        String classPath = System.getProperty("java.class.path");
        System.out.println("===================================");
        System.out.println(classPath);
        System.setProperty("java.class.path", classPath);
        memoryUsePrint(new Object());
    }

    public static void memoryUsePrint(Object obj) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("访问数据库");

        stopWatch.stop();
        stopWatch.start("复制数据");

        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint(TimeUnit.SECONDS));
        long totalB = GraphLayout.parseInstance(obj).totalSize();
        double totalKb = NumberUtil.div(totalB, 1024);
        double totalMb = NumberUtil.div(totalB, 1024 * 1024);
        System.out.println(StrUtil.format("当前对象所占用内存大小为: \n [{}] byte  \n [{}] kb \n [{}] mb", String.valueOf(totalB), String.valueOf(totalKb), String.valueOf(totalMb)));
    }
}
